package cn.mw.cmdb.template.strategy.manager;

import cn.mw.cmdb.template.enums.TemplateImportExportTypeEnum;
import cn.mw.cmdb.template.param.MwTemplateConfigurationParam;
import cn.mw.cmdb.template.strategy.TemplateImportExportHandler;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * @description 模板导入导出策略管理
 */
@Component
@Slf4j
public class TemplateImportExportManage {

    Map<TemplateImportExportTypeEnum, TemplateImportExportHandler> handlerMap = new HashMap<>();

    @Autowired
    private ApplicationContext applicationContext;

    @PostConstruct
    public void init(){
        Map<String, TemplateImportExportHandler> beans = applicationContext.getBeansOfType(TemplateImportExportHandler.class);
        for (TemplateImportExportHandler bean : beans.values()) {
            TemplateImportExportTypeEnum typeEnum = bean.handlerType();
            handlerMap.put(typeEnum,bean);
        }
    }

    public void exportTemplate(TemplateImportExportTypeEnum importExportTypeEnum, MwTemplateConfigurationParam param, HttpServletResponse response) throws Exception {
        if(importExportTypeEnum == null){return;}
        handlerMap.get(importExportTypeEnum).exportTemplate(param,response);
    }

    public void importTemplate(TemplateImportExportTypeEnum importExportTypeEnum, MwTemplateConfigurationParam param, MultipartFile file) throws Exception {
        if(importExportTypeEnum == null){return;}
        handlerMap.get(importExportTypeEnum).importTemplate(param,file);
    }
}
